<template>
  <div class="main">
    <input type="file" @change="handleFileChange" />
  </div>
</template>

<script>
/*eslint-disable*/
import DXFParser from "dxf-parser";
import { toGeojson } from "../api/toGeojson.js";
import { ElMessage } from "element-plus";

export default {
  name: "main",
  data() {
    return {};
  },
  methods: {
    // 文件输入处理
    handleFileChange(event) {
      // 数据类型限制
      if (!this.typeControl(event)) return;
      // 数据读取
      this.readData(event)
        .then((res) => {
          console.log(res);
          // 数据处理
          this.handleData(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 数据类型限制
    typeControl(event) {
      const file = event.target.files[0];
      // 仅支持上传.dxf文件
      if (file.name.split(".")[file.name.split(".").length - 1] != "dxf") {
        ElMessage({
          message: "仅支持上传.dxf文件，请重试！",
          type: "error",
        });
        return false;
      }
      return true;
    },
    // 数据读取
    readData(event) {
      let reader = new FileReader();
      reader.readAsText(event.target.files[0]);
      return new Promise((res, rej) => {
        // 读取成功
        reader.onload = (e) => {
          let content = e.target.result;
          let parser = new DXFParser();
          let dxf = parser.parseSync(content);
          console.log(dxf);
          res(toGeojson(dxf));
        };
        // 读取失败
        reader.onerror = () => {
          rej("文件读取失败：" + reader.error);
        };
      });
    },
    // 数据处理
    handleData(data) {
      // 数据图层整理
      let layerList = [""];
      data.features.forEach((element) => {
        // 图层整理
        let layerNewFlag = true;
        layerList.forEach((layer) => {
          if (layer === String(element.properties.layer)) layerNewFlag = false;
        });
        if (layerNewFlag) layerList.push(element.properties.layer);
      });
      layerList.splice(0, 1);
      // 按数据图层归类
      let dataListByLayer = [];
      // 图层筛选
      layerList.forEach((layer) => {
        let list = [];
        data.features.forEach((entity) => {
          if (String(entity.properties.layer) === layer) list.push(entity);
        });
        // 载入
        dataListByLayer.push({ layer, list });
      });
      console.log(dataListByLayer);
    },
  },
};
</script>

<style>
.main {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}
</style>

